﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FindIt.Web.Authentication;
using FindIt.Domain.Contracts;
using Microsoft.Practices.Unity;
using FindIt.Web.Models.User;

namespace FindIt.Web.Controllers {
    public class AuthController : Controller {
        private readonly IFormsAuthentication _formsAuthentication;
        private readonly IUserServices _userServices;


        [InjectionConstructor]
        public AuthController(IFormsAuthentication formsAuthentication,
                              IUserServices userServices) {
            this._formsAuthentication = formsAuthentication;
            this._userServices = userServices;
        }

        //
        // GET: /Auth/

        public ActionResult SignIn() {
            var model = new LoginModel();

            return View(model);
        }

        [HttpPost]
        public ActionResult SignIn(LoginModel model, string returnUrl) {
            if (ModelState.IsValid) {
                if (_userServices.ValidateUser(model.Email, model.Password)) {

                    var user = _userServices.GetAuthenticatedUser(model.Email);
                    _formsAuthentication.SetAuthCookie(this.HttpContext,
                                                           UserAuthenticationTicketBuilder.CreateAuthenticationTicket(
                                                               user));
                    if (!String.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
                        return Redirect(returnUrl);
                    else
                        return RedirectToAction("List", "Digest");
                }
            }

            return View(model);
        }


        public ActionResult SignOut() {
            this._formsAuthentication.Signout();
            return this.RedirectToAction("Index", "Home");
        }
    }
}
